package com.yoshino.leetcode.improve40.fourteenth;

class MovingAverage {

    int[] list;
    int pre = 0, tail = 0, size, sum = 0, com = 0;
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        list = new int[size + 1];
        this.size = size;
    }
    
    public double next(int val) {
        if (com == size) {
            // 满了
            sum -= list[pre];
            pre = (pre + 1) % size;
            list[tail] = val;
            tail = (tail + 1) % size;
        } else {
            list[tail] = val;
            tail = (tail + 1) % size;
            com++;
        }
//        if ((tail + 1) % size == pre) {
//            sum -= list[pre];
//            pre = (pre + 1) % size;
//            list[tail] = val;
//            tail = (tail + 1) % size;
//        } else {
//            list[tail] = val;
//            tail = (tail + 1) % size;
//        }
        sum += val;
        return (sum + 0.0) / com;
    }
}

/**
 * Your MovingAverage object will be instantiated and called as such:
 * MovingAverage obj = new MovingAverage(size);
 * double param_1 = obj.next(val);
 */